package com.budwk.app.sqfw.services.customservice.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.text.StrFormatter;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.budwk.app.common.config.AppException;
import com.budwk.app.oss.services.SysOssService;
import com.budwk.app.sqfw.bo.PdfResourceSortBO;
import com.budwk.app.sqfw.component.CommunityStreetComponent;
import com.budwk.app.sqfw.constants.CommonConstants;
import com.budwk.app.sqfw.constants.DictConstants;
import com.budwk.app.sqfw.dto.SqfwSummaryPdfExcelCollForAdminDTO;
import com.budwk.app.sqfw.enums.DownLoadFileNameEnum;
import com.budwk.app.sqfw.enums.SupportBusinessTypeEnum;
import com.budwk.app.sqfw.models.Sqfw_cenSusPaper;
import com.budwk.app.sqfw.models.Sqfw_completeflow;
import com.budwk.app.sqfw.models.Sqfw_formSummary;
import com.budwk.app.sqfw.models.Sqfw_formSummary_new;
import com.budwk.app.sqfw.services.SqfwCompleteflowService;
import com.budwk.app.sqfw.services.SqfwFormSummaryService;
import com.budwk.app.sqfw.services.SqfwFormsummaryNewService;
import com.budwk.app.sqfw.services.common.SqfwCustomForAdminCommonService;
import com.budwk.app.sqfw.vo.CheckDataForAdminVO;
import com.budwk.app.sqfw.vo.GenerateExcelUrlVO;
import com.budwk.app.sqfw.vo.GenerateWordAndPdfUrlVO;
import com.budwk.app.sqfw.vo.SqfwCustomForAdminCommonVO;
import com.budwk.app.sqfwDoc.bo.ExcelCreateConfig;
import com.budwk.app.sqfwDoc.codeGenerator.excelGenerate.BaseTemplateExcelGenerator;
import com.budwk.app.sqfwV2.component.ShawenTownComponent;
import com.budwk.app.sqfwV2.dto.shawenTown.ShawenTownSafetyPdfDTO;
import com.budwk.app.sqfwV2.service.ShawenTownSafetyService;
import com.budwk.app.sqfwV2.service.shawenTown.ShawenTownSafetyExcelService;
import com.budwk.app.sys.models.Sys_user;
import com.budwk.app.sys.services.SysDictService;
import com.budwk.app.sys.services.SysLogService;
import com.budwk.app.sys.services.SysUserService;
import com.budwk.app.sys.vo.SysDictVO;
import com.budwk.app.util.adminUtils.CommonCheckUtils;
import com.budwk.app.util.poiUtils.CommonFormOfficeForAdminUtils;
import com.budwk.app.util.poiUtils.CommonFormOfficeUtils;
import com.budwk.starter.common.page.Pagination;
import com.budwk.starter.common.result.ResultCode;
import com.budwk.starter.security.utils.SecurityUtil;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.nutz.aop.interceptor.ioc.TransAop;
import org.nutz.dao.Cnd;
import org.nutz.dao.entity.annotation.Table;
import org.nutz.dao.sql.Criteria;
import org.nutz.dao.util.cri.SqlExpressionGroup;
import org.nutz.dao.util.cri.Static;
import org.nutz.ioc.aop.Aop;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Strings;

import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;

/**
 * @program: dfxy-community
 * @description: 沙文镇安全排查（后台管理系统）
 * @author: LJT
 * @create: 2024-03-13 17:03
 **/
@IocBean(name = "ShaWenZhenSecurityForAdminService")
@Slf4j
public class ShaWenZhenSecurityForAdminServiceImpl extends ShawenTownSafetyExcelService implements SqfwCustomForAdminCommonService {

    @Inject
    private CommunityStreetComponent communityStreetComponent;

    @Inject
    private SqfwFormsummaryNewService sqfwFormsummaryNewService;

    @Inject
    private SqfwFormSummaryService sqfwFormSummaryService;

    @Inject
    private SqfwCompleteflowService sqfwCompleteflowService;

    @Inject
    private SysLogService sysLogService;

    @Inject
    private SysUserService sysUserService;

    @Inject
    private ShawenTownSafetyService shawenTownSafetyService;

    @Inject
    private SysDictService sysDictService;

    @Inject
    private SysOssService sysOssService;

    private final static String RESIDEN_HOUSE = "residen_house";

    private final static String RESIDEN_HOUSE_NAME = "居民住宅";

    @Override
    public Pagination list(SqfwCustomForAdminCommonVO bean) {
        if (StringUtils.isEmpty(bean.getType())) {
            throw new AppException(ResultCode.NOT_FOUND.getMsg());
        }
        long startTime = System.currentTimeMillis();
        // 构造查询条件
        Criteria criteria = buildQueryCond(bean);
        log.info("ShaWenZhenSecurityForAdminServiceImpl-list-SQL: {}", criteria.toString());
        Pagination pagination = sqfwFormsummaryNewService.listPage(bean.getPageNo(), bean.getPageSize(), criteria);
        // 查询流程pdf
        List<Sqfw_formSummary_new> sqfwCustomForAdminCommonVOList = pagination.getList(Sqfw_formSummary_new.class);
        if (ObjectUtil.isNotEmpty(sqfwCustomForAdminCommonVOList)) {
            List<SqfwCustomForAdminCommonVO> finalCommonVOList = new ArrayList<SqfwCustomForAdminCommonVO>();
            Map<String, String> pdfUrlMap = CommonCheckUtils.getPdfUrlByFlowId(sqfwCustomForAdminCommonVOList);
            // 字典列表查询
            Map<String, String> dictCodesMap = CommonCheckUtils.getDictInfoMaps(Arrays.asList(DictConstants.SHAWEN_BUSSINESS_SCOPE));
            sqfwCustomForAdminCommonVOList.forEach(source -> {
                SqfwCustomForAdminCommonVO target = new SqfwCustomForAdminCommonVO();
                BeanUtil.copyProperties(source, target);
                target.setPdfUrl(pdfUrlMap.get(target.getSqfwFlowId()));
                ShawenTownSafetyPdfDTO shawenSafetyDTO = JSONObject.parseObject(target.getParamData(), ShawenTownSafetyPdfDTO.class);
                if (ObjectUtil.isNotEmpty(shawenSafetyDTO) && ObjectUtil.isNotEmpty(shawenSafetyDTO.getSmallBusinessEstablishment()) ) {
                    String mainBusinessScope = shawenSafetyDTO.getSmallBusinessEstablishment().getMainBusinessScope();
                    if (StringUtils.isNotEmpty(mainBusinessScope)) {
                        String[] mainBusinessScopes = mainBusinessScope.split(",");
                        StringBuffer sb = new StringBuffer();
                        for (String mainBusiness : mainBusinessScopes) {
                            String finalMainBusiness = dictCodesMap.get(mainBusiness);
                            if (StringUtils.isNotEmpty(finalMainBusiness)) {
                                sb.append(finalMainBusiness).append(",");
                            } else {
                                sb.append(mainBusinessScope).append(",");
                            }
                        }
                        target.setMainBusinessScopeName(sb.substring(0, sb.length() - 1));
                    } else if ("false".equals(shawenSafetyDTO.getSmallBusinessEstablishment().getKey())) {
                        target.setMainBusinessScopeName(RESIDEN_HOUSE_NAME);
                    }
                }
                if (Strings.isNotBlank(target.getCheckStatus())
                        && CommonCheckUtils.TO_DO_CHECK_OUT.equals(target.getCheckStatus())
                        && null != target.getFillDate()) {
                    Date offsetDate = DateUtil.parse(CommonFormOfficeForAdminUtils.DATE_FORMAT.format(DateUtil.offsetDay(new Date(), -CommonFormOfficeForAdminUtils.TIME_OUT)));
                    Date thisFillDate = DateUtil.parse(CommonFormOfficeForAdminUtils.DATE_FORMAT.format(target.getFillDate()));
                    if (offsetDate.compareTo(thisFillDate) < 0) {
                        target.setCheckStatus(CommonCheckUtils.CHECK_OUT);
                    }
                }
                finalCommonVOList.add(target);
            });
            pagination.setList(finalCommonVOList);
        }
        log.info("ShaWenZhenSecurityForAdminServiceImpl-list-耗时: {}ms", System.currentTimeMillis() - startTime);
        return pagination;
    }

    @Override
    @Aop(TransAop.READ_COMMITTED)
    public int delete(String id) {
        Sqfw_formSummary_new sqfwFormSummaryNew = sqfwFormsummaryNewService.fetch(id);
        if (sqfwFormSummaryNew == null) {
            throw new AppException(ResultCode.NULL_DATA_ERROR.getMsg());
        }
        batchDeleteDataNew(SecurityUtil.getUserId(), sqfwFormSummaryNew);
        return 0;
    }

    @Override
    @Aop(TransAop.READ_COMMITTED)
    public int batchDelete(List<String> ids) {
        if (ids == null || ids.size() == 0) {
            throw new AppException(ResultCode.NULL_DATA_ERROR.getMsg());
        }
        // 查询数据
        Cnd cnd = Cnd.NEW();
        cnd.and(Sqfw_formSummary::getId, "in", ids);
        List<Sqfw_formSummary_new> newList = sqfwFormsummaryNewService.query(cnd);
        if (newList.isEmpty()) {
            throw new AppException(ResultCode.NULL_DATA_ERROR.getMsg());
        }
        String userId = SecurityUtil.getUserId();
        // 异步执行删除操作
        if (!newList.isEmpty()) {
            ExecutorService executorService = Executors.newSingleThreadExecutor();
            CompletableFuture.runAsync(() -> {
                for (Sqfw_formSummary_new sqfwFormSummaryNew : newList) {
                    batchDeleteDataNew(userId, sqfwFormSummaryNew);
                }
            }, executorService);
            executorService.shutdown();
        }
        return newList.size();
    }

    @Override
    public int update(Sqfw_formSummary_new sqfwFormsummaryNew) {
        return 0;
    }

    @Override
    public List<GenerateExcelUrlVO> downloadExcel(List<ExcelCreateConfig> excelConfigList, SqfwCustomForAdminCommonVO bean) {
        if (StringUtils.isEmpty(bean.getType())) {
            throw new AppException(ResultCode.NOT_FOUND.getMsg());
        }
        // 如果formSummaryNewIdList为空，根据条件下载，否则根据勾选id下载
        if (ObjectUtil.isEmpty(bean.getFormSummaryNewIdList()) || bean.getFormSummaryNewIdList().size() <= 0) {
            Criteria criteria = buildQueryCond(bean);
            List<Sqfw_formSummary_new> summaryNewList = sqfwFormsummaryNewService.query(criteria);
            if (summaryNewList.size() > 0) {
                bean.setFormSummaryNewIdList(sqfwFormsummaryNewService.query(criteria).stream().map(Sqfw_formSummary_new::getId).collect(Collectors.toList()));
            } else {
                return new ArrayList<GenerateExcelUrlVO>();
            }
        } else {
            Cnd cnd = Cnd.NEW();
            // 时间
            if (ObjectUtil.isNotEmpty(bean.getQueryStartTime()) && ObjectUtil.isNotEmpty(bean.getQueryEndTime())) {
                cnd.and(Sqfw_formSummary_new::getFillDate, ">=", communityStreetComponent.handleStartQueryTime(bean.getQueryStartTime()));
                cnd.and(Sqfw_formSummary_new::getFillDate, "<=", communityStreetComponent.handleEndQueryTime(bean.getQueryEndTime()));
            }
            cnd.and(Sqfw_formSummary_new::getId, "IN", bean.getFormSummaryNewIdList());
            List<Sqfw_formSummary_new> summaryNewList = sqfwFormsummaryNewService.query(cnd);
            if (summaryNewList.size() > 0) {
                bean.setFormSummaryNewIdList(summaryNewList.stream().map(Sqfw_formSummary_new::getId).collect(Collectors.toList()));
            } else {
                return new ArrayList<GenerateExcelUrlVO>();
            }
        }
        if (excelConfigList.get(0).getOnlyGenerateTemplateFlag() == true) {
            bean.setFormSummaryNewIdList(Collections.emptyList());
        }
        return super.generateExcelForAdmin(excelConfigList, SecurityUtil.getUserId(), bean.getFormSummaryNewIdList());
    }

    @Override
    public GenerateWordAndPdfUrlVO downloadPdf(List<ExcelCreateConfig> excelConfigList, SqfwCustomForAdminCommonVO bean) {
        if (StringUtils.isEmpty(bean.getType())) {
            throw new AppException(ResultCode.NOT_FOUND.getMsg());
        }
        GenerateWordAndPdfUrlVO generateWordAndPdfUrlVO = new GenerateWordAndPdfUrlVO();
        if (excelConfigList.get(0).getOnlyGenerateTemplateFlag()) {
            String fileName = DownLoadFileNameEnum.SAFETY_INVESTIGATE_RENOVATE.getName() + ".docx";
            String filepath = "sqfwV2/shawenTown/template/shawenTownSafeWordTemplate.docx";
            generateWordAndPdfUrlVO.setPdfUrl(sysOssService.upload(CommonFormOfficeUtils.getTempPdfFile(filepath), fileName).getUrl());
            return generateWordAndPdfUrlVO;
        } else {
            // 如果formSummaryNewIdList为空，根据条件下载，否则根据勾勾选id下载
            if (ObjectUtil.isEmpty(bean.getFormSummaryNewIdList()) || bean.getFormSummaryNewIdList().size() <= 0) {
                Criteria criteria = buildQueryCond(bean);
                List<Sqfw_formSummary_new> summaryNewList = sqfwFormsummaryNewService.query(criteria);
                if (summaryNewList.size() > 0) {
                    bean.setFormSummaryNewIdList(summaryNewList.stream().map(Sqfw_formSummary_new::getId).collect(Collectors.toList()));
                } else {
                    return new GenerateWordAndPdfUrlVO();
                }
            }
            List<SqfwSummaryPdfExcelCollForAdminDTO> summaryIdServiceList = new ArrayList<SqfwSummaryPdfExcelCollForAdminDTO>();
            for (String id : bean.getFormSummaryNewIdList()) {
                SqfwSummaryPdfExcelCollForAdminDTO sqfwSummaryPdfExcelCollForAdminDTO = new SqfwSummaryPdfExcelCollForAdminDTO();
                sqfwSummaryPdfExcelCollForAdminDTO.setSumId(id);
                sqfwSummaryPdfExcelCollForAdminDTO.setServiceType(bean.getType());
                summaryIdServiceList.add(sqfwSummaryPdfExcelCollForAdminDTO);
            }
            generateWordAndPdfUrlVO.setPdfUrl(generatePdfColl(summaryIdServiceList));
        }
        return generateWordAndPdfUrlVO;
    }

    @Override
    public List<GenerateExcelUrlVO> downloadPdfList
            (List<ExcelCreateConfig> excelConfigList, SqfwCustomForAdminCommonVO bean) {
        return null;
    }

    @Override
    public Criteria buildQueryCond(SqfwCustomForAdminCommonVO bean) {
        Criteria cri = Cnd.cri();
        SqlExpressionGroup criSql = cri.where();
        if (StringUtils.isEmpty(bean.getType())) {
            throw new AppException(ResultCode.NOT_FOUND.getMsg());
        }
        // 组装查询条件
        if (StringUtils.isNotBlank(bean.getPageOrderName()) && Strings.isNotBlank(bean.getPageOrderBy())) {
            if (bean.getPageOrderBy().equals(CommonConstants.ASC)) {
                cri.getOrderBy().asc(bean.getPageOrderName());
            }
            if (bean.getPageOrderBy().equals(CommonConstants.DESC)) {
                cri.getOrderBy().desc(bean.getPageOrderName());
            }
        } else {
            cri.getOrderBy().desc(Sqfw_formSummary_new::getFillDate);
        }
        // 类型
        criSql.andEquals(SqfwCustomForAdminCommonVO::getType, bean.getType());

        Sys_user sysUser = sysUserService.fetch(SecurityUtil.getUserId());
        if (ObjectUtils.isEmpty(sysUser)) {
            throw new AppException(ResultCode.USER_NOT_FOUND.getMsg());
        }
        // 区域5级检查
        CommonCheckUtils.checkAreaRange(criSql);
        // 省
        if (StringUtils.isNotBlank(bean.getProvince()) && !CommonCheckUtils.ZHISHU.equals(bean.getProvince())) {
            criSql.andEquals(SqfwCustomForAdminCommonVO::getProvince, bean.getProvince());
        }
        // 市
        if (StringUtils.isNotBlank(bean.getCity()) && !CommonCheckUtils.ZHISHU.equals(bean.getCity())) {
            criSql.andEquals(SqfwCustomForAdminCommonVO::getCity, bean.getCity());
        }
        // 区
        if (StringUtils.isNotBlank(bean.getDistrict()) && !CommonCheckUtils.ZHISHU.equals(bean.getDistrict())) {
            criSql.andEquals(SqfwCustomForAdminCommonVO::getDistrict, bean.getDistrict());
        }
        // 街道
        if (StringUtils.isNotBlank(bean.getCounty()) && !CommonCheckUtils.ZHISHU.equals(bean.getCounty())) {
            criSql.andEquals(SqfwCustomForAdminCommonVO::getCounty, bean.getCounty());
        }
        // 辖区
        if (StringUtils.isNotBlank(bean.getCommunity()) && !CommonCheckUtils.ZHISHU.equals(bean.getCommunity())) {
            criSql.andEquals(Sqfw_formSummary_new::getCommunity, bean.getCommunity());
        }
        // 时间
        if (ObjectUtil.isNotEmpty(bean.getQueryStartTime()) && ObjectUtil.isNotEmpty(bean.getQueryEndTime())) {
            criSql.andBetween(Sqfw_formSummary_new::getFillDate,
                    communityStreetComponent.handleStartQueryTime(bean.getQueryStartTime()),
                    communityStreetComponent.handleEndQueryTime(bean.getQueryEndTime()));
        }
        // 全局搜索
        if (StringUtils.isNotEmpty(bean.getQueryAll())) {
            SqlExpressionGroup address = Cnd.exps(new Static("param_data->>'address' like '%" + bean.getQueryAll() + "%'"));
            SqlExpressionGroup operator = Cnd.exps(new Static("param_data->>'operator' like '%" + bean.getQueryAll() + "%'"));
            SqlExpressionGroup operatorTelephone = Cnd.exps(new Static("param_data->>'operatorTelephone' like '%" + bean.getQueryAll() + "%'"));
            SqlExpressionGroup county = Cnd.exps(new Static("county like '%" + bean.getQueryAll() + "%'"));
            SqlExpressionGroup community = Cnd.exps(new Static("community like '%" + bean.getQueryAll() + "%'"));
            SqlExpressionGroup createUserName = Cnd.exps(new Static("create_user_name like '%" + bean.getQueryAll() + "%'"));
            SqlExpressionGroup mainBusinessScope = Cnd.exps(new Static("param_data->>'mainBusinessScope' like '%" + bean.getQueryAll() + "%'"));
            SqlExpressionGroup placeName = Cnd.exps(new Static("param_data->'smallBusinessEstablishment'->>'placeName' like '%" + bean.getQueryAll() + "%'"));
            criSql.and(address.or(operator).or(operatorTelephone).or(county).or(community).or(createUserName).or(mainBusinessScope).or(placeName));
        }
        // 需要排除的数据
        criSql.andNotEquals(Sqfw_formSummary_new::getFillDate, CommonConstants.WASTE_CREATE_TIME);

        // 地址
        if (StringUtils.isNotBlank(bean.getAddress())) {
            criSql.andEquals("param_data->>'address'", bean.getAddress());
        }
        // 负责人
        if (StringUtils.isNotBlank(bean.getOperator())) {
            criSql.andEquals("param_data->>'operator'", bean.getOperator());
        }
        // 负责人电话
        if (StringUtils.isNotEmpty(bean.getOperatorTelephone())) {
            criSql.andEquals("param_data->>'operatorTelephone'", bean.getOperatorTelephone());
        }
        // 检查人员
        if (StringUtils.isNotEmpty(bean.getCreateUserName())) {
            criSql.andEquals(Sqfw_formSummary_new::getCreateUserName, bean.getCreateUserName());
        }
        // 是否小型生产场所
        if (StringUtils.isNotEmpty(bean.getSmallBusinessEstablishment())) {
            criSql.andEquals("param_data->'smallBusinessEstablishment'->>'key'", bean.getSmallBusinessEstablishment());
        }
        // 是否有电动车
        if (StringUtils.isNotEmpty(bean.getElectricBicycle())) {
            criSql.andEquals("param_data->'electricBicycle'->>'key'", bean.getElectricBicycle());
        }
        // 是否存在隐患
        if (ObjectUtil.isNotEmpty(bean.getIssueStatus())) {
            if ("0".equals(bean.getIssueStatus())) {
                criSql.andEquals("param_data->>'issueStatus'", "false");
            } else if ("1".equals(bean.getIssueStatus())) {
                criSql.andEquals("param_data->>'issueStatus'", "true");
            }
        }
        // 经营范围
        if (ObjectUtil.isNotEmpty(bean.getMainBusinessScope())) {
            if (RESIDEN_HOUSE.equals(bean.getMainBusinessScope())) {
                criSql.andEquals("param_data->'smallBusinessEstablishment'->>'key'", "false");
            } else {
                criSql.andEquals("param_data->>'mainBusinessScope'", bean.getMainBusinessScope());
            }
        }
        // 场所名称
        if (ObjectUtil.isNotEmpty(bean.getPlaceName())) {
            criSql.andEquals("param_data->'smallBusinessEstablishment'->>'placeName'", bean.getPlaceName());
        }
        return cri;
    }

    @Override
    public List<CheckDataForAdminVO> checkDataInfoList(SqfwCustomForAdminCommonVO bean) {
        if (StringUtils.isEmpty(bean.getType())) {
            throw new AppException(ResultCode.NOT_FOUND.getMsg());
        }
        // 如果formSummaryNewIdList为空，根据条件下载，否则根据勾勾选id下载
        if (ObjectUtil.isEmpty(bean.getFormSummaryNewIdList()) || bean.getFormSummaryNewIdList().size() <= 0) {
            Criteria criteria = buildQueryCond(bean);
            List<Sqfw_formSummary_new> summaryNewList = sqfwFormsummaryNewService.query(criteria);
            if (summaryNewList.size() > 0) {
                bean.setFormSummaryNewIdList(summaryNewList.stream().map(Sqfw_formSummary_new::getId).collect(Collectors.toList()));
            } else {
                return new ArrayList<CheckDataForAdminVO>();
            }
        }

        // 1 获取所有字典数据
        List<SysDictVO> vos = sysDictService.listDictByCode(DictConstants.SHAWEN_EXCEL_COLLECTION);
        //2 按照社区服务id查询数据
        List<Sqfw_formSummary_new> list = queryBySummaryIdAndType(bean.getFormSummaryNewIdList(), SupportBusinessTypeEnum.BATYUN_SAFE.getName());
        // 检查数据是否可生成
        List<CheckDataForAdminVO> results = new ArrayList<>();
        for (SysDictVO vo : vos) {
            getDownFileTypesResVo(results, list, vo);
        }
        // 安全排查表pdf
        CheckDataForAdminVO resVo = new CheckDataForAdminVO();
        resVo.setFileName(DownLoadFileNameEnum.SHAWEN_INVESTIGATE_RENOVATE.getName() + ".pdf");
        resVo.setFileIdentity(DownLoadFileNameEnum.SHAWEN_INVESTIGATE_RENOVATE.getCode());
        resVo.setCreateConditionFlag(false);
        List<Sqfw_formSummary_new> finalSummaryNewList = sqfwFormsummaryNewService.query(Cnd.where(Sqfw_formSummary_new::getId, "IN", bean.getFormSummaryNewIdList()));
        List<String> sqfwFlowIds = finalSummaryNewList.stream().map(Sqfw_formSummary_new::getSqfwFlowId).collect(Collectors.toList());
        Cnd cnd = Cnd.NEW();
        cnd.and(Sqfw_completeflow::getId, "IN", sqfwFlowIds);
        cnd.and(Sqfw_completeflow::getResourcePath, "!=", "creating");
        cnd.and(Sqfw_completeflow::getResourcePath, "!=", "error");
        Integer pdfCount = sqfwCompleteflowService.count(cnd);
        if (pdfCount > 0) {
            resVo.setCreateConditionFlag(true);
        }
        results.add(resVo);
        return results;
    }

    @Override
    public void reGeneratePdf(String id) {
        shawenTownSafetyService.reGeneratePDF(id);
    }

    /**
     * 生成pdf合集
     *
     * @param conditionList
     * @return
     */
    public String generatePdfColl(List<SqfwSummaryPdfExcelCollForAdminDTO> conditionList) {
        List<PdfResourceSortBO> pdfBoList = Lists.newArrayList();
        Map<String, SqfwSummaryPdfExcelCollForAdminDTO> fromFlowDTOMap = Maps.newHashMap();
        for (SqfwSummaryPdfExcelCollForAdminDTO sqfwSummaryPdfExcelCollForAdminDTO : conditionList) {
            fromFlowDTOMap.put(sqfwSummaryPdfExcelCollForAdminDTO.getSumId(), sqfwSummaryPdfExcelCollForAdminDTO);
        }
        // 首先查询存储于sqfw_complete_flow中的数据
        if (fromFlowDTOMap.size() > 0) {
            Cnd cnd = Cnd.NEW();
            cnd.and("id", "in", fromFlowDTOMap.keySet());
            cnd.orderBy("fill_date", "asc");
            // 新表数据
            List<Sqfw_formSummary_new> formSummaryNewList = sqfwFormsummaryNewService.query(cnd);
            // 老表数据
            List<Sqfw_formSummary> formSummaryOldList = sqfwFormSummaryService.query(cnd);
            Map<String, Date> completeFlowIdDateMap = formSummaryNewList.stream()
                    .collect(Collectors.toMap(Sqfw_formSummary_new::getSqfwFlowId, Sqfw_formSummary_new::getFillDate));
            List<String> flowIdList = formSummaryNewList.stream().map(Sqfw_formSummary_new::getSqfwFlowId).collect(Collectors.toList());
            List<String> flowIdOldList = formSummaryOldList.stream().map(Sqfw_formSummary::getSqfwFlowId).collect(Collectors.toList());
            flowIdList.addAll(flowIdOldList);
            Cnd flowCnd = Cnd.NEW();
            flowCnd.and("id", "in", flowIdList);
            List<Sqfw_completeflow> completeFlowList = sqfwCompleteflowService.query(flowCnd);
            for (Sqfw_completeflow completeFlow : completeFlowList) {
                if (!completeFlow.getResourcePath().startsWith("/")) {
                    continue;
                }
                PdfResourceSortBO bo = new PdfResourceSortBO();
                Date fillDate = completeFlowIdDateMap.get(completeFlow.getId());
                bo.setSortDate(fillDate == null ? new Date() : fillDate);
                bo.setSqfwId(completeFlow.getSqfwId());
                bo.setPdfPath(completeFlow.getResourcePath());
                bo.setServiceType(completeFlow.getFileType());
                pdfBoList.add(bo);
            }
        }
        // 将这些文档按照时间先后顺序进行排序
        pdfBoList.sort(Comparator.comparing(PdfResourceSortBO::getSortDate));
        List<String> pdfPathList = pdfBoList.stream().map(PdfResourceSortBO::getPdfPath).collect(Collectors.toList());
        // 用于生成文件规则
        Set<String> serviceTypeTotalSet = conditionList.stream().map(SqfwSummaryPdfExcelCollForAdminDTO::getServiceType).collect(Collectors.toSet());
        String fileNameTemplate = "{}_{}";
        String fileNamePrefix = DownLoadFileNameEnum.SHAWEN_INVESTIGATE_RENOVATE.getName();
        String fileName = StrFormatter.format(fileNameTemplate, fileNamePrefix, DateUtil.format(new Date(), "yyyyMMddHHmmss"));
        return CommonFormOfficeUtils.createConvergePdfAndUpload(pdfPathList, fileName);
    }

    /**
     * 批量删除
     *
     * @param userId
     * @param data
     */
    private void batchDeleteDataNew(String userId, Sqfw_formSummary_new data) {
        //1 记录日志
        sysLogService.insertDelLog(userId, JSONObject.toJSONString(data), Sqfw_cenSusPaper.class.getAnnotation(Table.class).value(),
                "com.budwk.app.sqfw.services.customservice.DaYingLuSecurityForAdminServiceImpl.batchDeleteDataNew",
                "com.budwk.app.sqfw.controllers.admin.DaYingLuSecurityForAdminController.batchDelete");
        // 2 删除数据
        sqfwCompleteflowService.deleteAndUpdateWO(data.getSqfwFlowId());
    }

    private List<Sqfw_formSummary_new> queryBySummaryIdAndType(List<String> ids, String type) {
        Cnd cnd = Cnd.NEW();
        SqlExpressionGroup where = cnd.where();
        where.andInStrList(Sqfw_formSummary_new::getId, ids)
                .andEquals(Sqfw_formSummary_new::getType, type);
        cnd.getOrderBy().desc(Sqfw_formSummary_new::getFillDate);
        return sqfwFormsummaryNewService.query(cnd);
    }

    private void getDownFileTypesResVo(List<CheckDataForAdminVO> results, List<Sqfw_formSummary_new> list, SysDictVO vo) {
        CheckDataForAdminVO resVo = new CheckDataForAdminVO();
        BaseTemplateExcelGenerator service = ShawenTownComponent.getService(vo.getCode());
        resVo.setFileIdentity(vo.getCode());
        resVo.setFileName(vo.getName());
        resVo.setCreateConditionFlag(false);
        assert service != null;
        List<Sqfw_formSummary_new> newList = service.generateNewData(list);
        resVo.setCreateConditionFlag(newList.size() > 0);
        results.add(resVo);
    }
}
